<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="isAll"/> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <Tr  v-for="(item,index) in goodList" :key="index" 
        :name="item.name"
        :index="index"
        :price="item.price"
        :num="item.num"
        :checked="item.checked"
        :all="isAll"
        @addBtn="addFn"
        @delBtn="delFn"
        @deletBtn="deletFn"
        @checks="checksFn"
        ></Tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <sum colspan="5" :list="goodList">
            
          </sum>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
  import sum from './components/sum.vue'
  import Tr from './components/Tr.vue'
export default {
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  components:{
    Tr,
    sum
  },
  computed:{
    isAll:{
      set(val) {
        this.goodList.forEach(item=>item.checked = val)
      },
      get() {
        return this.goodList.every(item =>item.checked)
      }
    }
  },
  methods:{
    checksFn(val,index){
      this.goodList[index].checked =val
    },
    addFn(num,index) {
      this.goodList[index].num = num + 1
    },
    delFn(num,index) {
      if(num === 1) {
        alert('不能再减了')
      } else {
        this.goodList[index].num = num -1
      }
    },
    deletFn(index) {
      this.goodList.splice(index,1)
    }
  }
};
</script>

<style>
</style>